package com.zjhn.ds.netty.handler;

import com.zjhn.ds.netty.ChannelGroups;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;


/**
 * @BelongsProject: ds_jlw
 * @BelongsPackage: com.zjhn.ds.netty.handler
 * @Author: sxt
 * @CreateTime: 2023-09-20  10:06
 * @Description:
 * @Version: 1.0
 */
@Slf4j
@ChannelHandler.Sharable
public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {

    /**
     * 当从客户端接收到一个消息时被调用
     * msg 解析后的数据信息
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object message) throws Exception {
        // TODO
        ByteBuf byteBuf = Unpooled.copiedBuffer("1", CharsetUtil.UTF_8);
        ChannelGroups.broadcast("test");
    }

    /**
     * 在与客户端的连接已经建立之后将被调用
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("====[INFO]========DeviceServerHandler====channelActive channel连接成功，远端地址为：{}", ctx.channel().remoteAddress());
    }


    /**
     * 客户端与服务端断开连接时调用
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        //关闭
        log.info("====[INFO]========DeviceServerHandler====channelInactive {} 客户端连接关闭...", ctx.channel().remoteAddress());
    }

    /**
     * 服务端接收客户端发送过来的数据结束之后调用
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    /**
     * 在处理过程中引发异常时被调用
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("====[INFO]========DeviceServerHandler====exceptionCaught remoteAddress: {},连接异常: {}", ctx.channel().remoteAddress(), cause);
    }
}
